package cn.lysoy.demo.jobs;

import cn.lysoy.demo.entity.RequestLog;
import cn.lysoy.demo.mappertest.RequestLogMapper;
import cn.lysoy.demo.utils.DateUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@EnableScheduling
@Component
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class RequestLogJob {
    private final RequestLogMapper requestLogMapper;

    @Scheduled(cron = "0 * * * * ?")
    @DS("logdb")
    @DSTransactional
    public void execute() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        Date beforeMin = DateUtils.getBeforeMin(now, 2);
        String formatBeforeTime = sdf.format(beforeMin);
        String formatNow = sdf.format(now);
        List<Map<String, Object>> requestIps = requestLogMapper.selectMaps(new QueryWrapper<RequestLog>()
                .select("request_ip AS requestIp", "COUNT(1) AS count")
                .between("request_date", formatBeforeTime, formatNow)
                .groupBy("requestIp"));
        List<Map<String, Object>> requests = requestLogMapper.selectMaps(new QueryWrapper<RequestLog>()
                .select("CONCAT(class_name,'.',method_name) AS requestMethod", "COUNT(1) AS count")
                .between("request_date", formatBeforeTime, formatNow)
                .groupBy("requestMethod"));
        log.info(formatBeforeTime+"-"+formatNow);
        for (Map<String, Object> requestIp : requestIps) {
            log.info("请求ip:{},请求次数{}", requestIp.get("requestIp"), requestIp.get("count"));
        }
        for (Map<String, Object> request : requests) {
            log.info("请求方法:{},请求次数{}", request.get("requestMethod"), request.get("count"));
        }
    }
}
